const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);

// WebSocket服务监听8088端口
const wss = new WebSocket.Server({ server, port: 8088 });
let clients = [];

wss.on('connection', function connection(ws) {
  clients.push(ws);
  ws.on('close', () => {
    clients = clients.filter(client => client !== ws);
  });
});

// HTTP接口监听8089端口，供云函数调用
const notifyServer = http.createServer((req, res) => {
  if (req.url === '/notifyNewOrder' && req.method === 'POST') {
    let body = '';
    req.on('data', chunk => { body += chunk; });
    req.on('end', () => {
      // 通知所有WebSocket客户端
      clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(JSON.stringify({ type: 'new_order' }));
        }
      });
      res.writeHead(200);
      res.end('ok');
    });
  } else {
    res.writeHead(404);
    res.end();
  }
});
notifyServer.listen(8089, () => {
  console.log('HTTP通知服务已启动，端口8089');
});

console.log('WebSocket服务已启动，端口8088'); 